<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Cache;

class District extends Model
{
    protected $table = 'district';

    /**
     * 根据id找到地区名
     * @param  [type] $key [description]
     * @return [type]      [description]
     */
   	public function cacheFindById($id){
   		$district = Cache::get(config('app.name').':district:'.$id);
   		if($district){
    		return $district;
    	}

    	$district = self::find($id);
    	if(!$district){
    		return false;
    	}
    	Cache::forever(config('app.name').':district:'.$id, $district);
    	return $district;
   	}

    /**
     * 获取所有地区,存在父子关系
     * @return [type] [description]
     */
    function getAllDistrict(){
        $provinces = Cache::get(config('app.name').':district:all');
        if(!$provinces){
            $provinces = District::where('district_id',0)->get();
            foreach ($provinces as $province) {
                $province->value = $province->id;
                $province->label = $province->name;
                $citys = District::where('district_id',$province->id)->get();
                unset($province->id,$province->name,$province->district_id);
                foreach ($citys as $city) {
                    $city->value = $city->id;
                    $city->label = $city->name;
                    $areas = District::where('district_id',$city->id)->get();
                    unset($city->id,$city->name,$city->district_id);
                    foreach ($areas as $area) {
                        $area->value = $area->id;
                        $area->label = $area->name;
                        unset($area->id,$area->name,$area->district_id);
                    }
                    $city->children = $areas;
                }
                $province->children = $citys;
            }
            Cache::forever(config('app.name').':district:all', $provinces);
        }
        return $provinces;
    }

    /**
     * 获取所有地区,数据无父子关系
     * @return [type] [description]
     */
    function getAllDistrictEqual(){
        $result = Cache::get(config('app.name').':district:all:equal');
        if(!$result){
            $provinces = self::where('district_id',0)->get();
            $result = ['province_list' =>[],'city_list' =>[],'county_list' => []];
            foreach ($provinces as $province) {
                $result['province_list'][$province->id] = $province->name;
                $citys = self::where('district_id',$province->id)->get();
                foreach ($citys as $city) {
                    $result['city_list'][$city->id] = $city->name;
                    $areas = self::where('district_id',$city->id)->get();
                    foreach ($areas as $area) {
                        $result['county_list'][$area->id] = $area->name;
                    }
                }
            }
            Cache::forever(config('app.name').':district:all:equal', $result);
        }
        return $result;
    }
}
